package com.tsinghuabigdata.edu.ddmath.module.login.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Length;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.tsinghuabigdata.edu.commons.http.HttpRequestException;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.ZxApplication;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.commons.http.InformMapping;
import com.tsinghuabigdata.edu.ddmath.commons.http.ResponseCode;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.fragment.MyBaseFragment;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginSuccessHandler;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.AppUtils;
import com.tsinghuabigdata.edu.ddmath.util.GlobalData;
import com.tsinghuabigdata.edu.ddmath.util.KeyboardUtil;
import com.tsinghuabigdata.edu.ddmath.util.PreferencesUtils;
import com.tsinghuabigdata.edu.ddmath.util.ValidatorUtils;
import com.tsinghuabigdata.edu.ddmath.view.FragmentActionbarView;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;
import com.tsinghuabigdata.edu.utils.NetworkUtils;

import java.util.List;

import roboguice.inject.InjectView;


/**
 * login
 * Created by Administrator on 2016/12/14.
 */

public class LoginFragment extends MyBaseFragment implements View.OnClickListener {
    private static final String TAG = "RegisterFragment";
    private View root;

    @InjectView(R.id.bt_enterdoudou)
    private Button btEnterdoudou;
    @Length(trim = true, max = 11, min = 11, message = "帐号不合法", sequence = 2)
    @NotEmpty(trim = true, message = "帐号不能为空", sequence = 1)
    @InjectView(R.id.et_phone)
    private EditText etPhone;
    @Length(trim = true, max = 20, min = 6, message = "密码最少6位，请重新输入", sequence = 2)
    @NotEmpty(trim = true, message = "密码不能为空", sequence = 1)
    @InjectView(R.id.et_passwd)
    private EditText etPasswd;

    @InjectView(R.id.tv_forget_pass)
    private TextView tvForgetPass;

    private FragmentActionbarView fragmentActionbarView;

    private Validator mValidator;

    private MyProgressDialog progressDialog;
    private String mAccessToken;
    private String mTeacherId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_login, container, false);
        return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();

        initValidator();
    }

    private void initValidator() {
        mValidator = new Validator(this);
        mValidator.setValidationListener(new Validator.ValidationListener() {
            @Override
            public void onValidationSucceeded() {
                KeyboardUtil.hidInput(getActivity());
                if (!ValidatorUtils.validateMobile(etPhone.getText().toString().trim())) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                login();
            }

            @Override
            public void onValidationFailed(List<ValidationError> errors) {
                for (ValidationError error : errors) {
                    ((EditText) error.getView()).setError(error.getFailedRules().get(0).getMessage(getContext()));
                }
            }
        });
    }

    private void login() {
        progressDialog.setMessage("正在登录...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        final String loginName = etPhone.getText().toString().trim();
        final String passwd = etPasswd.getText().toString().trim();
        new LoginModel().login(getContext(), loginName, passwd, new RequestListener<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                progressDialog.dismiss();
                if (loginInfo == null) {
                    AlertManager.toast(getContext(), "用户名或密码错误");
                } else {
                    LoginSuccessHandler.loginSuccessHandler(getContext(), loginName, passwd);
                    finish();
                    goFragment(new UsercenterFragment());
                    GlobalData.setLoginChange(true);
                }
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                if (AppUtils.isNoNetwork() || NetworkUtils.isNoConnection(ex)) {
                    AlertManager.toast(getContext(), getString(R.string.no_connection));
                } else if (response.getCode() != ResponseCode._10000 && response.getInform() != null) {
                    if (response.getInform().contains("student is null")) {
                        AlertManager.toast(getContext(), "获取个人信息失败");
                    } else {
                        AlertManager.toast(getContext(), InformMapping.getInstance().get(response.getInform()));
                    }
                } else if (ex instanceof HttpRequestException) {
                    if (((HttpRequestException) ex).getRequest().getStatusCode() == 412 || ((HttpRequestException) ex).getRequest().getStatusCode() == 401) {
                        AlertManager.toast(getContext(), "用户名或密码错误");
                    } else {
                        AlertManager.toast(getContext(), getString(R.string.server_error));
                    }
                } else {
                    AlertManager.toast(getContext(), getString(R.string.server_error));
                }
            }
        });
    }

    private void initView() {
        progressDialog = new MyProgressDialog(getContext());

        fragmentActionbarView = (FragmentActionbarView) root.findViewById(R.id.fr_actionbar);
        fragmentActionbarView.setLeftTitle("返回");
        fragmentActionbarView.setTitle("登录");
        fragmentActionbarView.setLeftIcon(R.drawable.ic_back);

        //actionbar listener
        View.OnClickListener actionbarListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.left_icon:
                    case R.id.bar_left_btn:
//                        AlertManager.toast(getActivity(), "left");
                        finish();
                        break;
                    case R.id.right_icon:
                    case R.id.bar_right_btn:
                        break;
                }
            }
        };
        fragmentActionbarView.setListener(actionbarListener);

        //记忆登录名
        etPhone.setText(PreferencesUtils.getString(getContext(), AppConst.LOGIN_NAME, ""));

        //listener
        btEnterdoudou.setOnClickListener(this);
        tvForgetPass.setOnClickListener(this);

    }


    private void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_enterdoudou:
                mValidator.validate();
                break;
            case R.id.tv_forget_pass:
                goFragment(new RecoverPassFragment());
                break;
        }
    }

}
